package com.example.user.service.Impl;

import com.example.model.user.User;
import com.example.user.domain.LoginUser;
import com.example.user.service.MenuService;
import com.example.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户" + username + "不存在");
        }
//        Set<GrantedAuthority> authorities  = getAuthoritiesOfRoles(user);
        Set<GrantedAuthority> authorities  = getAuthoritiesOfPerms(user);
        return new LoginUser(user, authorities);
    }

    /**
     * 粗粒度：以角色作为认证
     * @param user
     * @return
     */
    private Set<GrantedAuthority> getAuthoritiesOfRoles(User user){
        return user.getRoles().stream()
                .map(role -> new SimpleGrantedAuthority(role.getRoleKey()))
                .collect(Collectors.toSet());
    }

    /**
     * 细粒度：以权限码作为认证
     * @param user
     * @return
     */
    private Set<GrantedAuthority> getAuthoritiesOfPerms(User user) {
        return menuService.getMenuPermsByUserId(user.getUserId()).stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toSet());
    }

}
